<?php


namespace App\Http\Controllers\Manage\Product;


use App\Http\Controllers\Controller;
use App\Http\Requests\Manage\Product\Index\RecordRequest;
use App\Http\Requests\Manage\Product\Index\RejectRequest;
use App\Http\Searchs\Manage\Product\IndexSearch;
use App\Repositories\Product;
use Illuminate\Support\Facades\DB;

class IndexController extends Controller
{
    /**
     * @var Product
     */
    private $product;

    /**
     * IndexController constructor.
     * @param Product $product
     */
    public function __construct(Product $product)
    {
        $this->product = $product;
    }

    /**
     * @param IndexSearch $search
     * @return \Illuminate\Http\JsonResponse
     * @author luffyzhao@vip.126.com
     */
    public function index(IndexSearch $search)
    {
        return $this->response(
            $this->product->paginate($search->toArray())
        );
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        return $this->response(
            $this->product->show($id)
        );
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function examine($id)
    {
        return $this->response(
            DB::transaction(function () use ($id) {
                $this->product->examine($id);
            })
        );
    }

    /**
     * @param RejectRequest $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function reject(RejectRequest $request, $id)
    {
        return $this->response(
            DB::transaction(function () use ($id, $request) {
                $this->product->reject($id, $request->input('reject'));
            })
        );
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function lock($id){
        return $this->response(
            DB::transaction(function () use ($id) {
                $this->product->upLock($id);
            })
        );
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function unlock($id){
        return $this->response(
            DB::transaction(function () use ($id) {
                $this->product->unlock($id);
            })
        );
    }


    /**
     * @param RecordRequest $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     * @throws \Throwable
     */
    public function updateRecord(RecordRequest $request, $id){
        return $this->response(
            $this->product->updateRecord($id, $request->only(['name', 'hs_code', 'country', 'unit', 'element', 'qy1', 'qy2', 'net_weight']))
        );
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function record($id){
        return $this->response(
            $this->product->record($id)
        );
    }
}
